package koala.kuangjiademo.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.dhy.xintent.XCommon;
import com.dhy.xintent.XIntent;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import koala.kuangjiademo.BuildConfig;
import koala.kuangjiademo.R;
import koala.kuangjiademo.data.AppSetting;
import koala.kuangjiademo.data.AppVersion;
import koala.kuangjiademo.data.User;
import koala.kuangjiademo.net.BooleanProgressStyle;
import koala.kuangjiademo.net.IResponseStatus;
import koala.kuangjiademo.net.OnFileProgressListener;
import koala.kuangjiademo.net.OnResponsePacketListener;
import koala.kuangjiademo.net.ProgressStyle;
import koala.kuangjiademo.net.RequestManager;

public class CheckVersionUtil {
    private static Map<String, Object> getParams(Context context) {
        Map<String, Object> map = new HashMap<>();
        map.put("packagename", context.getPackageName());
        map.put("versiontype", String.valueOf(BuildConfig.DEBUG ? 0 : 1));
        map.put("versioncode", String.valueOf(getVersionCode(context)));
        map.put("showCount", 1);
        return map;
    }

    public static void checkVersion(Context context, final OnResponsePacketListener<AppVersion.Data> listener) {
        RequestManager.checkAppVersion(getParams(context), listener);
    }

    public static void autoCheckVersion(Context context) {
        checkVersion(context, new OnResponsePacketListener<AppVersion.Data>(context, false, false) {
            @Override
            protected ProgressStyle getProgressStyle() {
                return new BooleanProgressStyle() {
                    @Override
                    public void onProgress(boolean progress) {

                    }
                };
            }

            @Override
            public void onResponsePacket(IResponseStatus status, AppVersion.Data response) {
                AppVersion appVersion = status.isSuccess() ? response.getAppVersion() : new AppVersion();
                EventBus.getDefault().postSticky(appVersion);
            }
        });
    }

    public static void shouldShowUpdateDialog(Context context) {
        AppVersion version = EventBus.getDefault().getStickyEvent(AppVersion.class);
        if (version != null) {
            boolean tip = false;
            if (version.haseNew()) {
                User user = XCommon.getSetting(context, AppSetting.user, User.class);
                if (user != null) {
                    String versionName = XCommon.getSetting(context, AppSetting.remindApkUpdate);
                    if (!version.getVersionName().equals(versionName)) tip = true;
                } else tip = true;
            }
            if (tip) {
                XIntent.startActivity(context, DownloadUpdateActivity.class, version);
            } else {
                EventBus.getDefault().removeStickyEvent(AppVersion.class);
            }
        }
    }

    public static void showUpdateTip(final Context context, @NonNull final AppVersion version) {
        if (version.haseNew()) {
            final Dialog dialog = Helper.showDialog(context, R.layout.apk_update_layout);
            View.OnClickListener listener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().removeStickyEvent(AppVersion.class);
                    dialog.dismiss();
                    if (v.getId() == R.id.buttonCommit) {
                        downloadThenInstallApk(context, version.getUrl());
                    } else {
                        if (!BuildConfig.DEBUG && version.isForceUpdate()) {
                            FlowUtil.finishAll(context);
                        } else if (context instanceof DownloadUpdateActivity) {
                            XCommon.updateSetting(context, AppSetting.remindApkUpdate, version.getVersionName());
                            ((DownloadUpdateActivity) context).finish();
                        }
                    }
                }
            };
            dialog.setCancelable(false);
            dialog.findViewById(R.id.buttonClose).setOnClickListener(listener);
            dialog.findViewById(R.id.buttonCommit).setOnClickListener(listener);
            XCommon.setTextWithFormat(dialog, R.id.textViewVersion, version.getVersionName());
            XCommon.setTextWithFormat(dialog, R.id.buttonCommit, version.getFileSize() / (1024 * 1024));//KB,MB
            XCommon.setTextWithFormat(dialog, R.id.textViewMessage, version.getUpdateInfo());
        } else EventBus.getDefault().removeStickyEvent(AppVersion.class);
    }

    private static void downloadThenInstallApk(final Context context, @NonNull final String url) {
        final File file = getUpdateApk(context);
        if (file == null) {//no sd card
            Toast.makeText(context, "没有SD卡，更新失败", Toast.LENGTH_LONG).show();
            return;
        }
        if (file.exists() && url.equals(XCommon.getSetting(context, AppSetting.apkUrl))) {
            //download finish
            Helper.installApk(context, file);
            return;
        }
        final Dialog dialog = Helper.showDialog(context, R.layout.apk_download_layout);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                Activity activity = (Activity) context;
                activity.finish();
            }
        });
        final ProgressBar progressBar = (ProgressBar) dialog.findViewById(R.id.progressBar);
        final TextView percent = (TextView) dialog.findViewById(R.id.textViewPercent);
        final TextView percentSize = (TextView) dialog.findViewById(R.id.textViewProgressSize);
        final int maxProgress = 10000;
        progressBar.setMax(maxProgress);
        RequestManager.download(context, url, file, new OnFileProgressListener() {
            final float unit = 1024 * 1024;//MB

            @Override
            public void onProgress(long progress, long total) {
                progressBar.setProgress((int) (maxProgress * progress / total));
                XCommon.setTextWithFormat(percent, 100.0f * progress / total);
                XCommon.setTextWithFormat(percentSize, new Object[]{progress / unit, total / unit});
            }

            @Override
            public void onFinish(boolean error, String message) {
                if (error) {
                    Log.i("download onFailure", "url: " + url);
                    Log.i("TAG", "error msg:" + message);
                    Toast.makeText(context, "下载失败", Toast.LENGTH_LONG).show();
                } else {
                    XCommon.updateSetting(context, AppSetting.apkUrl, url);
                    Helper.installApk(context, file);
                }
                dialog.dismiss();
            }
        });
    }

    @Nullable
    private static File getUpdateApk(Context context) {
        File dir = context.getExternalCacheDir();
        if (dir != null) {
            return new File(dir, "update.apk");
        }
        return null;
    }

    public static String getVersionName() {
        return BuildConfig.VERSION_NAME;
    }

    public static int getVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception ignored) {
            return -1;
        }
    }
}
